package com.rslai.commons.validator.jsonvalidator.validators;

import com.rslai.commons.validator.jsonvalidator.schema.Any;
import org.apache.commons.lang.StringUtils;
import org.junit.Assert;

import java.math.BigDecimal;

import static org.hamcrest.Matchers.comparesEqualTo;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;

/**
 * JSON校验器，Java的基本数据验器
 */
public class ValueValidator extends Validator {
    public static final String VALIDATOR_NAME = "value";
    private String parentKey;
    private Object value;

    /**
     * 构造函数
     * @param parentKey parentKey
     * @param value value
     */
    public ValueValidator(String parentKey, Object value) {
        this.parentKey = parentKey;
        this.value = value;
    }

    /**
     * 校验JSON对象
     * @param object 待验证的JSON对象
     */
    @Override
    public void doValidate(Object object) {
        if (!(value instanceof Any)) {
            if (object instanceof Number) {
                if (value instanceof BigDecimal) {
                    Assert.assertThat(getMessage(parentKey), new BigDecimal(object.toString()), is(comparesEqualTo((BigDecimal) value)));
                } else {
                    Assert.assertThat(getMessage(parentKey), new BigDecimal(object.toString()), is(equalTo(value)));
                }
            } else {
                Assert.assertThat(getMessage(parentKey), object, is(equalTo(value)));
            }
        }
    }

    /**
     * 返回校验名称
     * @return 校验名称
     */
    @Override
    public String name() {
        return VALIDATOR_NAME;
    }

    /**
     * 返回parentKey
     * @param parentKey parentKey
     * @return parentKey
     */
    private String getMessage(String parentKey) {
        if (StringUtils.isBlank(parentKey)) {
            return "";
        }
        return StringUtils.trim(parentKey);
    }

}
